using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

using SBPweb.Modules.Modularity;

namespace SBPweb.Modules.ModuleExplorer
{
	public class ModuleDescriptorCheckListBox : CheckedListBox
	{
        public ModuleDescriptorCheckListBox()
        {
            this.Sorted = true;
        }

		protected override void OnDrawItem(DrawItemEventArgs e)
		{
			if (this.Items.Count > 0 && this.Items[e.Index] is ModuleInfo)
			{
				ModuleInfo mi = this.Items[e.Index] as ModuleInfo;
				e.DrawBackground();

				System.Drawing.Rectangle checkRect = new System.Drawing.Rectangle(e.Bounds.X, e.Bounds.Y, e.Bounds.Height, e.Bounds.Height);
				System.Drawing.Rectangle checkBorderRect = new System.Drawing.Rectangle(e.Bounds.X + 1, e.Bounds.Y + 1, e.Bounds.Height - 2, e.Bounds.Height - 2);
				System.Drawing.Rectangle checkGlyphRect = new System.Drawing.Rectangle(e.Bounds.X + 2, e.Bounds.Y + 1, e.Bounds.Height - 2, e.Bounds.Height - 2);
				System.Drawing.Rectangle bulletGlyphRect = new System.Drawing.Rectangle(e.Bounds.X + 2, e.Bounds.Y + 1, e.Bounds.Height - 1, e.Bounds.Height - 1);

				if (this.Enabled)
				{
					e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Window, checkRect);
					if (this.CheckedIndices.Contains(e.Index))
					{
						if (mi.ModuleDescriptor.Loaded)
						{
							ControlPaint.DrawMenuGlyph(e.Graphics, checkGlyphRect, MenuGlyph.Checkmark, e.ForeColor, e.BackColor);
						}
						else
						{
							ControlPaint.DrawMenuGlyph(e.Graphics, bulletGlyphRect, MenuGlyph.Bullet, e.ForeColor, e.BackColor);
						}
					}
					e.Graphics.DrawRectangle(System.Drawing.SystemPens.WindowText, checkBorderRect);
				}

				System.Drawing.Brush textBrush = System.Drawing.SystemBrushes.WindowText;
				if (e.Index == this.SelectedIndex)
				{
					textBrush = System.Drawing.SystemBrushes.HighlightText;
				}
				if (mi.ModuleDescriptor != null && mi.ModuleDescriptor.Loaded && !mi.AllowUnload && mi.Module != null)
				{
					textBrush = System.Drawing.SystemBrushes.GrayText;
				}
				string text = String.Format("{0} ({1})", mi.ModuleDescriptor.AssemblyName, mi.ModuleDescriptor.FileVersion);
				e.Graphics.DrawString(text, e.Font, textBrush, checkRect.Right, e.Bounds.Y);
			}
			else
			{
				base.OnDrawItem(e);
			}
		}

		protected override void OnItemCheck(ItemCheckEventArgs ice)
		{
			if (this.Items.Count > 0 && this.Items[ice.Index] is ModuleInfo)
			{
				ModuleInfo mi = this.Items[ice.Index] as ModuleInfo;
				if (mi.ModuleDescriptor.Loaded && !mi.AllowUnload && ice.CurrentValue == CheckState.Checked)
				{
					ice.NewValue = CheckState.Checked;
				}
			}
			base.OnItemCheck(ice);
		}

		public bool IsModuleInfoChecked(ModuleInfo mi)
		{
			return this.CheckedIndices.Contains(this.Items.IndexOf(mi));
		}
	}
}
